package com.example.gpstest.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bin.david.form.core.SmartTable;
import com.example.gpstest.DataBean.DataSnrBean;
import com.example.gpstest.R;
import com.example.gpstest.Utils.ExcelUtil;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnInputConfirmListener;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class GPSSnrActivity extends AppCompatActivity {

    @BindView(R.id.btn_Start)
    Button btnStart;
    @BindView(R.id.btn_Stop)
    Button btnStop;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    @BindView(R.id.tv_gpsnumber)
    TextView tvGpsnumber;
    @BindView(R.id.tv_glonassnumber)
    TextView tvGlonassnumber;
    @BindView(R.id.tv_dbnumber)
    TextView tvDbnumber;
    @BindView(R.id.btn_derive)
    Button btnDerive;
    @BindView(R.id.smartTable)
    SmartTable smartTable;
    @BindView(R.id.tv_galileonumber)
    TextView tvGalileonumber;
    private LocationManager locationManagerSnr;
    private ArrayList<GpsSatellite> numSatelliteList = new ArrayList();//有效搜星数量
    int countnumber = 0;
    int Gpsnumber, Glonassnumber, Dbnumber, Galileonumber;
    private List<DataSnrBean> dataTestBeanList = new ArrayList<>();
    private List<DataSnrBean> dataTestBeanListAll = new ArrayList<>();
    private ArrayList<List<String>> list1 = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gpssnr);
        ButterKnife.bind(this);
        if (locationManagerSnr == null) {
            locationManagerSnr = (LocationManager) getSystemService(LOCATION_SERVICE);
        }
    }

    @OnClick({R.id.btn_Start, R.id.btn_Stop, R.id.btn_derive})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_Start:
                countnumber = 0;
                if (list1.size()>0){
                    list1.clear();
                }
                initLocation();
                btnStart.setEnabled(false);
                break;
            case R.id.btn_Stop:
                stopGPSListener();
                btnStart.setEnabled(true);
                break;
            case R.id.btn_derive:
                new XPopup.Builder(this)
                        .asInputConfirm("保存", "默认保存的路径地址:/storage/emulated/0/GPSTestFile/", "excelSNR.xls", null,
                                new OnInputConfirmListener() {
                                    @Override
                                    public void onConfirm(String text) {
                                        if (text.contains(".xls")) {
                                            getExcel(text);
                                        } else {
                                            ExcelUtil.ShortToast(GPSSnrActivity.this, "保存失败，不是xls文件格式");
                                        }
                                    }
                                })
                        .show();
                break;
        }
    }

    private void initLocation() {
        //判断GPS是否正常启动
        if (!locationManagerSnr.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(this, "请开启GPS导航", Toast.LENGTH_SHORT).show();
            //返回开启GPS导航设置界面
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, 0);
            return;
        }
        //5000位最小的时间间隔，1为最小位移变化；也就是说每隔5000ms会回调一次位置信息
        locationManagerSnr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 3, locationListener);
        //添加卫星状态改变监听
        locationManagerSnr.addGpsStatusListener(gpsStatusListener);
    }

    LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

    private GpsStatus.Listener gpsStatusListener = new GpsStatus.Listener() {
        @Override
        public void onGpsStatusChanged(int event) {
            switch (event) {
                //卫星状态改变
                case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                    dataTestBeanList.clear();
                    //获取当前状态
                    @SuppressLint("MissingPermission") GpsStatus gpsStatus = locationManagerSnr.getGpsStatus(null);
                    //获取卫星颗数的默认最大值
                    int maxSatellites = gpsStatus.getMaxSatellites();
                    //获取所有的卫星
                    Iterator<GpsSatellite> iters = gpsStatus.getSatellites().iterator();
                    //卫星颗数统计
                    int count = 0;
                    int countnum = 0;
                    Glonassnumber = 0;
                    Gpsnumber = 0;
                    Dbnumber = 0;
                    Galileonumber = 0;
                    StringBuilder sb = new StringBuilder();
                    countnumber++;
                    while (iters.hasNext() && count <= maxSatellites) {
                        count++;
                        GpsSatellite s = iters.next();
                        //卫星的信噪比
                        float snr = s.getSnr();
                        if (s.getPrn() <= 64 || (s.getPrn() >= 120 && s.getPrn() <= 138)) {
                                dataTestBeanList.add(new DataSnrBean(s.getPrn(), "GPS", snr, countnumber + ""));
                        } else if (s.getPrn() >= 201 && s.getPrn() <= 261) {
                                dataTestBeanList.add(new DataSnrBean(s.getPrn(), "BEIDOU", snr, countnumber + ""));

                        } else if (s.getPrn() >= 65 && s.getPrn() <= 88) {
                                dataTestBeanList.add(new DataSnrBean(s.getPrn(), "Glonass", snr, countnumber + ""));

                        } else if (s.getPrn() >= 301 && s.getPrn() <= 336) {
                                dataTestBeanList.add(new DataSnrBean(s.getPrn(), "Galileo", snr, countnumber + ""));
                        }
                        if (snr != 0.0) {
                            countnum++;
                        }
                        //sb.append("第").append(count).append("颗").append("：").append(snr).append("\n");

                    }
                    Comparator<DataSnrBean> comparator = new Comparator<DataSnrBean>() {
                        public int compare(DataSnrBean s1, DataSnrBean s2) {
                            if (s1.getName2().equals(s2.getName2())) {
                                return (int) s2.getName3() - (int) (s1.getName3());
                            } else {
                                return Integer.valueOf(s1.getName1()) - Integer.valueOf(s2.getName1());
                            }
                        }
                    };
                    Collections.sort(dataTestBeanList, comparator);
                    if (countnumber <= 301) {
                        List<String> list = new ArrayList<>();
                        dataTestBeanListAll.clear();
                        for (int i = 0; i < dataTestBeanList.size(); i++) {
                            String name1=dataTestBeanList.get(i).getName2()+"("+dataTestBeanList.get(i).getName1()+")";
                            String name2=dataTestBeanList.get(i).getName3()+"";
                            if (name1.contains("GPS") && Gpsnumber<5){
                                list.add(name1);
                                list.add(name2);
                                dataTestBeanListAll.add(new DataSnrBean(dataTestBeanList.get(i).getName1(), dataTestBeanList.get(i).getName2(), dataTestBeanList.get(i).getName3(), dataTestBeanList.get(i).getName4()));
                                Gpsnumber++;
                            }else if (name1.contains("BEIDOU") && Dbnumber<5){
                                list.add(name1);
                                list.add(name2);
                                dataTestBeanListAll.add(new DataSnrBean(dataTestBeanList.get(i).getName1(), dataTestBeanList.get(i).getName2(), dataTestBeanList.get(i).getName3(), dataTestBeanList.get(i).getName4()));
                                Dbnumber++;
                            }else if (name1.contains("Glonass") && Glonassnumber<5){
                                list.add(name1);
                                list.add(name2);
                                dataTestBeanListAll.add(new DataSnrBean(dataTestBeanList.get(i).getName1(), dataTestBeanList.get(i).getName2(), dataTestBeanList.get(i).getName3(), dataTestBeanList.get(i).getName4()));
                                Glonassnumber++;
                            }else if (name1.contains("Galileo") && Galileonumber<5){
                                list.add(name1);
                                list.add(name2);
                                dataTestBeanListAll.add(new DataSnrBean(dataTestBeanList.get(i).getName1(), dataTestBeanList.get(i).getName2(), dataTestBeanList.get(i).getName3(), dataTestBeanList.get(i).getName4()));
                                Galileonumber++;
                            }
                        }
                        list1.add(list);
                        smartTable.setData(dataTestBeanListAll);
                        tvNumber.setText("卫星数量:" + count + " 卫星SNR>0数量:" + countnum);
                        tvGpsnumber.setText(Gpsnumber + "");
                        tvGlonassnumber.setText(Glonassnumber + "");
                        tvDbnumber.setText(Dbnumber + "");
                        tvGalileonumber.setText(Galileonumber+"");
                    } else {
                        btnStart.setEnabled(true);
                        stopGPSListener();
                    }
                    break;
                default:
                    break;
            }
        }
    };


    private void getExcel(String excelFileName) {
        String filePath = Environment.getExternalStorageDirectory().getPath() + "/GPSTestFile";
        File files = new File(filePath);
        if (!files.exists()) {
            if (files.mkdirs()) {

            } else {
                Toast.makeText(GPSSnrActivity.this, "创建失败", Toast.LENGTH_LONG).show();
                return;
            }
        }
        String[] title = {"卫星类型(PNR)", "SNR"};
        String resultPath = files.getAbsolutePath() + "/" + excelFileName;
        Log.e("rultPath", resultPath);
        ExcelUtil.initExcel(resultPath, title);
        File moudleFile = ExcelUtil.writeObjListToExcel1(list1, resultPath);
        if (moudleFile != null) {
            Toast.makeText(GPSSnrActivity.this, "保存到本地" + resultPath, Toast.LENGTH_LONG).show();
        }
    }

    //停止gps监听
    public void stopGPSListener() {
        if (locationManagerSnr != null) {
            locationManagerSnr.removeUpdates(locationListener);
            locationManagerSnr.removeGpsStatusListener(gpsStatusListener);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopGPSListener();
    }
}
